import { defineStore } from 'pinia'
import { authApi, userApi } from '@/services/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户基本信息
    user: null,
    token: localStorage.getItem('token') || '',
    isLoggedIn: false,
    
    // 用户扩展信息
    profile: null,
    addresses: [],
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      notifications: {
        system: true,
        order: true,
        activity: true,
        service: true
      }
    },
    
    // 消息和通知
    unreadCount: 0,
    notifications: [],
    
    // 用户行为记录
    favoriteServices: [],
    favoriteMerchants: [],
    recentlyViewed: {
      services: [],
      merchants: []
    },
    
    // 订单统计
    orderStats: {
      total: 0,
      pending: 0,
      completed: 0,
      cancelled: 0
    },
    
    // 积分和优惠券
    points: 0,
    coupons: [],
    
    // 应用状态
    isLoading: false,
    lastLoginTime: null
  }),

  getters: {
    // 用户认证状态
    isAuthenticated: (state) => {
      return !!(state.token && state.user && state.isLoggedIn)
    },
    
    // 用户显示名称
    displayName: (state) => {
      if (!state.user) return '游客'
      return state.user.nickname || state.user.username || state.user.phone
    },
    
    // 用户头像
    avatar: (state) => {
      return state.user?.avatar || state.profile?.avatar || '/default-avatar.jpg'
    },
    
    // 是否有未读消息
    hasUnreadMessages: (state) => state.unreadCount > 0,
    
    // 格式化未读消息数
    unreadCountText: (state) => {
      if (state.unreadCount === 0) return ''
      if (state.unreadCount > 99) return '99+'
      return state.unreadCount.toString()
    },
    
    // 用户等级
    userLevel: (state) => {
      const points = state.points || 0
      if (points >= 10000) return { level: 'VIP', name: 'VIP会员', color: '#gold' }
      if (points >= 5000) return { level: 'Gold', name: '金牌用户', color: '#ffd700' }
      if (points >= 1000) return { level: 'Silver', name: '银牌用户', color: '#c0c0c0' }
      return { level: 'Bronze', name: '普通用户', color: '#cd7f32' }
    },
    
    // 可用优惠券数量
    availableCouponsCount: (state) => {
      const now = new Date()
      return state.coupons.filter(coupon => 
        !coupon.used && new Date(coupon.expireTime) > now
      ).length
    },
    
    // 是否为新用户
    isNewUser: (state) => {
      if (!state.user?.createdAt) return false
      const createTime = new Date(state.user.createdAt)
      const now = new Date()
      const daysDiff = (now - createTime) / (1000 * 60 * 60 * 24)
      return daysDiff <= 7 // 注册7天内为新用户
    }
  },

  actions: {
    // 设置用户信息
    setUser(user) {
      this.user = user
      this.isLoggedIn = !!user
      if (user) {
        this.lastLoginTime = new Date()
      }
    },

    // 设置令牌
    setToken(token) {
      this.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },

    // 设置用户详细信息
    setProfile(profile) {
      this.profile = profile
    },

    // 设置未读消息数量
    setUnreadCount(count) {
      this.unreadCount = Math.max(0, count)
    },

    // 增加未读消息数量
    increaseUnreadCount(increment = 1) {
      this.unreadCount += increment
    },

    // 减少未读消息数量
    decreaseUnreadCount(decrement = 1) {
      this.unreadCount = Math.max(0, this.unreadCount - decrement)
    },

    // 清空未读消息
    clearUnreadCount() {
      this.unreadCount = 0
    },

    // 添加通知
    addNotification(notification) {
      this.notifications.unshift({
        id: Date.now(),
        timestamp: new Date(),
        read: false,
        ...notification
      })
      
      // 增加未读计数
      this.increaseUnreadCount()
      
      // 限制通知数量
      if (this.notifications.length > 100) {
        this.notifications = this.notifications.slice(0, 100)
      }
    },

    // 标记通知为已读
    markNotificationAsRead(notificationId) {
      const notification = this.notifications.find(n => n.id === notificationId)
      if (notification && !notification.read) {
        notification.read = true
        this.decreaseUnreadCount()
      }
    },

    // 更新用户偏好设置
    updatePreferences(preferences) {
      this.preferences = {
        ...this.preferences,
        ...preferences
      }
      // 保存到本地存储
      localStorage.setItem('userPreferences', JSON.stringify(this.preferences))
    },

    // 添加收藏服务
    addFavoriteService(serviceId) {
      if (!this.favoriteServices.includes(serviceId)) {
        this.favoriteServices.push(serviceId)
        this.saveFavorites()
      }
    },

    // 移除收藏服务
    removeFavoriteService(serviceId) {
      const index = this.favoriteServices.indexOf(serviceId)
      if (index > -1) {
        this.favoriteServices.splice(index, 1)
        this.saveFavorites()
      }
    },

    // 添加收藏商家
    addFavoriteMerchant(merchantId) {
      if (!this.favoriteMerchants.includes(merchantId)) {
        this.favoriteMerchants.push(merchantId)
        this.saveFavorites()
      }
    },

    // 移除收藏商家
    removeFavoriteMerchant(merchantId) {
      const index = this.favoriteMerchants.indexOf(merchantId)
      if (index > -1) {
        this.favoriteMerchants.splice(index, 1)
        this.saveFavorites()
      }
    },

    // 保存收藏到本地存储
    saveFavorites() {
      localStorage.setItem('favoriteServices', JSON.stringify(this.favoriteServices))
      localStorage.setItem('favoriteMerchants', JSON.stringify(this.favoriteMerchants))
    },

    // 添加最近浏览
    addRecentlyViewed(type, item) {
      const list = this.recentlyViewed[type]
      const existingIndex = list.findIndex(i => i.id === item.id)
      
      if (existingIndex > -1) {
        // 如果已存在，移到前面
        list.splice(existingIndex, 1)
      }
      
      list.unshift({
        ...item,
        viewedAt: new Date()
      })
      
      // 限制数量
      if (list.length > 20) {
        list.splice(20)
      }
      
      // 保存到本地存储
      localStorage.setItem('recentlyViewed', JSON.stringify(this.recentlyViewed))
    },

    // 更新订单统计
    updateOrderStats(stats) {
      this.orderStats = {
        ...this.orderStats,
        ...stats
      }
    },

    // 更新积分
    updatePoints(points) {
      this.points = Math.max(0, points)
    },

    // 增加积分
    addPoints(amount, reason = '') {
      this.points += amount
      
      // 添加积分获得通知
      this.addNotification({
        type: 'points',
        title: '积分获得',
        message: `恭喜您获得 ${amount} 积分${reason ? `：${reason}` : ''}`,
        icon: 'gift'
      })
    },

    // 更新优惠券列表
    updateCoupons(coupons) {
      this.coupons = coupons || []
    },

    // 添加优惠券
    addCoupon(coupon) {
      this.coupons.unshift(coupon)
      
      // 添加优惠券获得通知
      this.addNotification({
        type: 'coupon',
        title: '优惠券获得',
        message: `您获得了新的优惠券：${coupon.name}`,
        icon: 'ticket'
      })
    },

    // 使用优惠券
    useCoupon(couponId) {
      const coupon = this.coupons.find(c => c.id === couponId)
      if (coupon) {
        coupon.used = true
        coupon.usedAt = new Date()
      }
    },

    // 登录
    async login(credentials) {
      try {
        this.isLoading = true
        
        const response = await authApi.login(credentials)
        
        // Spring Boot 返回的JWT响应结构
        const { data } = response
        const token = data.token || data.accessToken
        const user = data.user || data.userInfo
        
        if (token) {
          this.setToken(token)
        }
        
        if (user) {
          this.setUser(user)
        } else {
          // 如果登录响应没有用户信息，使用token获取用户信息
          await this.fetchUserInfo()
        }
        
        return response
        
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 注册
    async register(userData) {
      try {
        this.isLoading = true
        
        const response = await authApi.register(userData)
        
        // Spring Boot 返回的注册响应
        const { data } = response
        const token = data.token || data.accessToken
        const user = data.user || data.userInfo || data
        
        if (token) {
          this.setToken(token)
        }
        
        if (user) {
          this.setUser(user)
        }
        
        // 新用户欢迎通知
        this.addNotification({
          type: 'welcome',
          title: '欢迎加入',
          message: `欢迎您，${user.nickname || user.username}！感谢您注册我们的洗护服务平台。`,
          icon: 'user'
        })
        
        // 新用户福利
        this.addPoints(100, '新用户注册奖励')
        
        return response
        
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 登出
    async logout() {
      try {
        // 尝试调用登出API
        try {
          await authApi.logout()
        } catch (error) {
          console.warn('登出API调用失败:', error)
        }
      } catch (error) {
        console.error('登出失败:', error)
      } finally {
        // 清除本地状态
        this.setToken('')
        this.setUser(null)
        this.setProfile(null)
        this.clearUnreadCount()
        this.notifications = []
        this.orderStats = { total: 0, pending: 0, completed: 0, cancelled: 0 }
        this.points = 0
        this.coupons = []
        
        // 清除本地存储
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('userPreferences')
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (!this.token) {
        return
      }

      try {
        let response
        try {
          response = await authApi.getUserInfo()
        } catch (error) {
          // API获取失败，静默处理
          return
        }

        const userInfo = response.data
        this.setUser(userInfo)
        this.setProfile(userInfo.profile)
        this.updateOrderStats(userInfo.orderStats || {})
        this.updatePoints(userInfo.points || 0)
        this.updateCoupons(userInfo.coupons || [])
        this.setUnreadCount(userInfo.unreadCount || 0)

        // 保存用户信息到本地存储
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      } catch (error) {
        // 如果token无效，清除登录状态
        if (error.response?.status === 401) {
          this.setToken('')
          this.setUser(null)
        }
      }
    },

    // 更新用户信息
    async updateUserInfo(updateData) {
      try {
        this.isLoading = true

        // 使用新的用户API
        const { userApi } = await import('@/services/api')
        const response = await userApi.updateUserProfile(updateData)

        this.setUser(response.data)
        return response
      } catch (error) {
        console.error('更新用户信息失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 修改密码
    async changePassword(passwordData) {
      try {
        this.isLoading = true

        const { userApi } = await import('@/services/api')
        const response = await userApi.changePassword(passwordData)

        return response
      } catch (error) {
        console.error('修改密码失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 更新手机号
    async updateMobile(mobileData) {
      try {
        this.isLoading = true

        const { userApi } = await import('@/services/api')
        const response = await userApi.updateMobile(mobileData)

        // 更新用户信息中的手机号
        if (this.user) {
          this.user.mobile = mobileData.mobile
        }

        return response
      } catch (error) {
        console.error('更新手机号失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 更新邮箱
    async updateEmail(emailData) {
      try {
        this.isLoading = true

        const { userApi } = await import('@/services/api')
        const response = await userApi.updateEmail(emailData)

        // 更新用户信息中的邮箱
        if (this.user) {
          this.user.email = emailData.email
        }

        return response
      } catch (error) {
        console.error('更新邮箱失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 实名认证
    async verifyRealName(verifyData) {
      try {
        this.isLoading = true

        const { userApi } = await import('@/services/api')
        const response = await userApi.verifyRealName(verifyData)

        // 更新用户认证状态
        if (this.user) {
          this.user.realNameVerified = true
          this.user.realName = verifyData.realName
        }

        return response
      } catch (error) {
        console.error('实名认证失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    },

    // 初始化用户数据
    async initializeUser() {
      // 从本地存储恢复用户偏好
      const storedPreferences = localStorage.getItem('userPreferences')
      if (storedPreferences) {
        try {
          this.preferences = {
            ...this.preferences,
            ...JSON.parse(storedPreferences)
          }
        } catch (error) {
          console.error('解析用户偏好失败:', error)
        }
      }

      // 从本地存储恢复收藏
      try {
        const favoriteServices = localStorage.getItem('favoriteServices')
        if (favoriteServices) {
          this.favoriteServices = JSON.parse(favoriteServices)
        }
        
        const favoriteMerchants = localStorage.getItem('favoriteMerchants')
        if (favoriteMerchants) {
          this.favoriteMerchants = JSON.parse(favoriteMerchants)
        }
        
        const recentlyViewed = localStorage.getItem('recentlyViewed')
        if (recentlyViewed) {
          this.recentlyViewed = JSON.parse(recentlyViewed)
        }
        
      } catch (error) {
        console.error('恢复本地数据失败:', error)
      }
    },

    // 检查认证状态
    async checkAuth() {
      if (!this.token) {
        return false
      }
      
      try {
        await this.fetchUserInfo()
        return this.isAuthenticated
      } catch (error) {
        console.error('检查认证状态失败:', error)
        return false
      }
    },

    // 发送短信验证码
    async sendSmsCode(phone) {
      try {
        const response = await authApi.sendSmsCode(phone)
        return response
      } catch (error) {
        console.error('发送验证码失败:', error)
        throw error
      }
    },

    // 验证码登录
    async loginWithCode(data) {
      try {
        this.isLoading = true
        
        const response = await authApi.loginWithCode(data)
        const { token, user } = response.data
        
        this.setToken(token)
        this.setUser(user)
        
        // 登录后获取用户详细信息
        await this.fetchUserInfo()
        
        return response
      } catch (error) {
        console.error('验证码登录失败:', error)
        throw error
      } finally {
        this.isLoading = false
      }
    }
  }
}) 